package test;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.ssl.PrivateKeyDetails;
import org.apache.http.ssl.PrivateKeyStrategy;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.ssl.TrustStrategy;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import java.io.File;
import java.io.IOException;
import java.net.Socket;
import java.security.*;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;

public class UploadOrDownUtil {
    private static final String UPLOAD_URL = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE";
    private static HttpClient hc = HttpClients.createDefault();
    //  private static HttpClient hcdd = HttpClientBuilder.create().build();

    /**
     * 文件上传
     *
     * @param filePath
     * @param accessToken
     * @param type
     * @return
     * @throws IOException
     */
    public static String upload(String filePath, String accessToken, String type) throws IOException {
        File file = new File(filePath);
        //存在且是文件
        if (file.exists() && file.isFile()) {
            String url = UPLOAD_URL.replace("ACCESS_TOKEN", accessToken).replace("TYPE", type);
            HttpPost httppost = new HttpPost(url);
            // httppost.addHeader("Connection", "keep-alive");
            //    httppost.addHeader("Accept", "*/*");
            String BOUNDARY = "----------" + System.currentTimeMillis();
            httppost.addHeader("Content-Type", "multipart/form-data;boundary="
                    + BOUNDARY);
            // httppost.setHeader("","");
            //  httppost.setEntity(new StringEntity("")); //放入body
            MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
            multipartEntityBuilder.setBoundary(BOUNDARY);
            // multipartEntityBuilder.setCharset(Charset.forName("utf-8"));//设置请求的编码格式
            //  multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);//设置浏览器兼容模式
            multipartEntityBuilder.addBinaryBody("media", file,
                    ContentType.APPLICATION_OCTET_STREAM, file
                            .getName());
            httppost.setEntity(multipartEntityBuilder.build());
            HttpResponse httpResponse = hc.execute(httppost);
            //httpResponse.getAllHeaders();
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            HttpEntity httpEntity = httpResponse.getEntity();
            //String s= IOUtils.toString(httpEntity.getContent());
            JSONObject jsonObj = JSON.parseObject(EntityUtils.toString(httpEntity, "utf-8"));
            System.out.println(jsonObj);
            String typeName = "media_id";
            if ("thumb".equals(type)) {
                typeName = type + "_media_id";
            }
            return jsonObj.getString(typeName);
        }
        return null;

    }

    public static void main(String[] args) throws IOException, KeyStoreException, CertificateException, NoSuchAlgorithmException, KeyManagementException, UnrecoverableKeyException {
    /*    String mediaId = upload("C:\\Users\\tangxinmao.DESKTOP-CSR4FB0\\Desktop\\111.jpg", WeixinUtil.getAccessToken().getToken(), "image");
        System.out.println(mediaId);*/

        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(FileUtils.openInputStream(new File("C:/Users/tangxinmao/Desktop/keys/cdhaixun.jks")), "tangbin45683968".toCharArray());


        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(FileUtils.openInputStream(new File("C:/Users/tangxinmao/Desktop/keys/clientkey.p12")), "tangbin45683968".toCharArray());

        SSLContext sslContext = SSLContexts.custom().useProtocol("TLS")
                .loadTrustMaterial(trustStore,
                        new TrustSelfSignedStrategy()
                ).loadKeyMaterial(keyStore, "tangbin45683968".toCharArray()
                ).build();

        HostnameVerifier hostnameVerifierAllowAll = new HostnameVerifier() {
            public boolean verify(String name, SSLSession session) {
                return true;
            }
        };
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                sslContext,
                SSLConnectionSocketFactory.getDefaultHostnameVerifier());
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory> create()
                .register("http", PlainConnectionSocketFactory.INSTANCE)
                .register("https", new SSLConnectionSocketFactory(sslContext)).build();
        PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        hc = HttpClients.custom().setSSLSocketFactory(sslsf).setConnectionManager(connManager).build();
        HttpPost httppost = new HttpPost("https://cdhaixun.com:8443/shop/userApp/getUser");
        httppost.setHeader("Content-Type", "application/json");
       // new UrlEncodedFormEntity(nvps,"utf-8");
        httppost.setEntity(new StringEntity("{\"id\":2284}"));
        HttpResponse httpResponse = hc.execute(httppost);
        HttpEntity httpEntity = httpResponse.getEntity();
        String s = IOUtils.toString(httpEntity.getContent());
        System.out.printf(s);
    }


}
